<?php
set_time_limit(0);ini_set('max_execution_time', 0);
//--------------------------处理每场比赛的tr函数------------------------------------------------------------------------------
/**
 * 欧洲指数
 * 取得所有公司的名,和开始与结束的指数
 * @date:2012.12.10
 */
function get_company_index($body){
	preg_match('/var data_str=(.+?);/s',$body, $body);//取得想要的信息块
	$array = json_decode(trim($body[1],"'"));
	$new_array = array();
	
	$myMaker = array("82","84","404");
	//$myMaker_name = array("立博","Interwetten","澳门","Marathon"," sports-1","YouWager","5Dimes");
	$myMaker_name = array("82"=>"立","43"=>"In","84"=>"澳","538"=>"Ma","404"=>"sp","320"=>"Yo","89"=>"5D","24"=>"99家");
	foreach ($array as $value) {
		$id = trim($value->MakerID);
		if(!in_array($id, $myMaker))
			continue;
		//$new_array[$id]["CompanyName"] = $value->CompanyName;
		$new_array[$id]["CompanyName"] = $myMaker_name[$id];
		$new_array[$id]["Start"] = $value->Start;
		$new_array[$id]["End"] = $value->End;
	}
	return $new_array;
}
/**
 * 取得亚洲盘口的数据
 */
function get_yaZhou_Pankou($body){
	preg_match("/data_str='(.+)';/",$body, $body);//取得想要的信息块
	$body_new = trim($body[1]);
	if(empty($body_new))
		return null;
	$array = json_decode($body_new,"'");
	if(empty($array))
		return null;
	//print_r($array);exit;
	$new_array = array();

	$myMaker = array("82","84","404");
	$myMaker_name = array("82"=>"立","43"=>"In","84"=>"澳","538"=>"Ma","404"=>"sp","320"=>"Yo","89"=>"5D","24"=>"99家");
	foreach ($array as $value) {
		$id = trim($value["MakerID"]);
		if(!in_array($id, $myMaker))
			continue;
		//$new_array[$id]["CompanyName"] = $value->CompanyName;
		$new_array[$id]["CompanyName"] = $myMaker_name[$id];
		
		$start = reset($value["spchangeHometeam"]);
		$end = end($value["spchangeHometeam"]);
		
		$new_array[$id]["Start"] = new stdClass();
		$new_array[$id]["Start"]->a = $start["Change"][0];
		$new_array[$id]["Start"]->b = $start["Boundary"];
		$new_array[$id]["Start"]->c = $start["Change"][1];
		
		$new_array[$id]["End"] = new stdClass();
		$new_array[$id]["End"]->a = $end["Change"][0];
		$new_array[$id]["End"]->b = $end["Boundary"];
		$new_array[$id]["End"]->c = $end["Change"][1];
	}
	return $new_array;
}
/**
 * 判断欧洲指数中的99家平均,最后是否大于2.25
 * @date:2012.12.10
 */
function isGt225($company_index = array()){
return true;
	if(!empty($company_index["24"]["End"])){
		foreach ($company_index["24"]["End"] as $value) {
			if(($value+1) < (2.25+1))
				return false;
		}
		return true;
	}
	return false;
}
/**
 * 将欧洲指数放到文中
 */
function insert_company_index($tr,$company_index,$yaZhou){
	$str = null;
	switch ($tr) {
		case 3:
			return company_index_add($company_index,$yaZhou,"82",true);
		case 4:
			return company_index_add($company_index,$yaZhou,"82",false);
		case 5:
			return company_index_add($company_index,$yaZhou,"43",true);
		case 6:
			return company_index_add($company_index,$yaZhou,"43",false);
		case 7:
			return company_index_add($company_index,$yaZhou,"84",true);
		case 8:
			return company_index_add($company_index,$yaZhou,"84",false);
		case 9:
			return company_index_add($company_index,$yaZhou,"538",true);
		case 10:
			return company_index_add($company_index,$yaZhou,"538",false);
			
		case 12:
			return company_index_add($company_index,$yaZhou,"404",true);
		case 13:
			return company_index_add($company_index,$yaZhou,"404",false);
		case 14:
			return company_index_add($company_index,$yaZhou,"320",true);
		case 15:
			return company_index_add($company_index,$yaZhou,"320",false);
		case 16:
			return company_index_add($company_index,$yaZhou,"89",true);
		case 17:
			return company_index_add($company_index,$yaZhou,"89",false);
		case 20:
			if(!isset($company_index["24"]["Start"]))
				return "";
			$str = "&nbsp;&nbsp;&nbsp;&nbsp;".$company_index["24"]["Start"]->home.sp(2);
			$str .= $company_index["24"]["Start"]->draw.sp(2);
			$str .= $company_index["24"]["Start"]->away."&nbsp;&nbsp;&nbsp;";
			$str .= $company_index["24"]["End"]->home.sp(2);
			$str .= $company_index["24"]["End"]->draw.sp(2);
			$str .= $company_index["24"]["End"]->away;
			return $str;
	}
}
/**
 * 将对应的欧指,亚盘放入文中
 * @param 欧洲指数 $company_index
 * @param 亚洲盘口 $yaZhou
 * @param 第几行 $key
 * @param 上或下 $f
 */
function company_index_add($company_index,$yaZhou,$key,$f){
	//print_r($yaZhou);exit;
	$str = "";
	if($f){
		if(!empty($company_index[$key])){
			$str.= $company_index[$key]["CompanyName"]."&nbsp;&nbsp;";
			$str.= $company_index[$key]["End"]->home;
			$str.= "&nbsp;&nbsp;".$company_index[$key]["End"]->draw;
			$str.= "&nbsp;&nbsp;".$company_index[$key]["End"]->away;
			$str.= "&nbsp;&nbsp;&nbsp;";
		}
		
		if(!empty($yaZhou[$key])){
			if(empty($str))
				$str.= $yaZhou[$key]["CompanyName"].sp(21);
			$str.= $yaZhou[$key]["Start"]->a;
			$str.= "&nbsp;".$yaZhou[$key]["Start"]->b;
			$str.= "&nbsp;".$yaZhou[$key]["Start"]->c;
		}
	}else{
		if(!empty($company_index[$key])){
			$str.= sp(4).$company_index[$key]["Start"]->home;
			$str.= "&nbsp;&nbsp;".$company_index[$key]["Start"]->draw;
			$str.= "&nbsp;&nbsp;".$company_index[$key]["Start"]->away;
		}
		if(!empty($yaZhou[$key])){
			if(empty($str))
				$str.= sp(23);
			else 
				$str.= "&nbsp;&nbsp;&nbsp;";
			$str.=  $yaZhou[$key]["End"]->a;
			$str.= "&nbsp;".$yaZhou[$key]["End"]->b;
			$str.= "&nbsp;".$yaZhou[$key]["End"]->c;
		}
	}
    return $str;          
}
function sp($n = 0){
	$sp = null;
	for ($i = 1; $i <= $n; $i++) {
		$sp.= "&nbsp;";
	}
	return $sp;
}
//通过传过来的html，将赛前积分放入数组中
/*
function get_top($html){
	preg_match_all('/<tr(.+?)<\/tr>/s', $html, $tr);
	
	$top = array();
	foreach ($tr[1] as $key=>$value) {
		if($key <= 0)
			continue;
		preg_match_all('/<td align(.+?)<\/td>/s', $value, $td);
		$key = strip_tags($td[0][0]);
		if(is_numeric($key))
			$top[$key] = strip_tags($td[0][1]);
		//if(strpos($value, "#FFFFB1"))
		//	$top["m"][strip_tags($td[0][0])] = strip_tags($td[0][1]);
	}
	return $top;
}
*/
//从新版得到排名
function get_top_new($body){
	preg_match('/ id="tr" >(.+?)<\/table>/s',$body, $body);//取得想要的信息块
	preg_match_all('/<tr(.+?)<\/tr>/s', $body[1], $tr);
	$top = array();
	foreach ($tr[1] as $key=>$value) {
		if($key < 0 || !strpos($value, "tbg01"))
			continue;
		preg_match_all('/<td width="13%(.+?)<\/td>/s', $value, $td);
		preg_match_all('/<td>(.+?)<\/td>/s', $value, $name22);
		$key = trim(strip_tags($td[0][0]));
		$name = trim($name22[1][0]);
		if(is_numeric($key) && strip_tags($name))
			$top[$key] = $name;
		//if(strpos($value, "#FFFFB1"))
		//	$top["m"][strip_tags($td[0][0])] = strip_tags($td[0][1]);
	}
	return $top;
}
/**
 * 处理排名
 * 如果有两个相同的字，就认为是同一个球队
 * @param 数组总排名 $top
 * @param 球队的名子 $name
 */
function top_go($top, $name, $fp, $team9){
	$name = trim($name);
	if(empty($top) || empty($name))
		return null;
	foreach ($top as $key => $value) {
		$value = trim($value);
		//排名球队和比赛中球队一样              和球队简称表符合                        大于3个字        &&   前3个字和排名里的一样
		if( $name == $value || (isset($team9[$name]) && $team9[$name] == $value) || (strlen($name) > 9 && mb_substr($name, 0, 3, 'utf-8') == $value ))
			return $key;
		
		/* if(similar_text($value, $name) >= 6)
			return $key; */
	}
	//fwrite($fp, "球队排名不存在,或简称不对:{$name}\r\n");
	//fwrite($fp, "'{$name}',");
	return null;
}
//排名的样式
function top_style($str = null){
	$str = trim($str);
	if($str<=9)
		$color = "0f0";
	else 
		$color = "f00";
	return empty($str)?null:"&nbsp;<span style='color:#{$color}'>(".$str.")</span>";
	//return empty($str)?null:"&nbsp;<span style='color:#0f0'>(".$str.")</span>";
}
//得到主场球队
function Zhuchang($body){
	/*
	preg_match('/teamnameJfen teamnameJfenL">(.+?)<\/dl>/s',$body, $left);
	preg_match('/teamnameJfen teamnameJfenR">(.+?)<\/dl>/s',$body, $right);
	$zhuChang_array = array();
	$zhuChang_array[] = trim(strip_tags($left[1]));
	$zhuChang_array[] = trim(strip_tags($right[1]));
	*/
	//preg_match('/<p style="color: #666666;">(.+?)<\/p>/s',$body, $bifen);
	
	preg_match('/<p class="gray6">(.+?)<\/p>/s',$body, $bifen);
	
	$zhuChang_array["bifen"] = "<span style='color:red;font-weight:bold'>{$bifen[1]}<\/span>";
	return $zhuChang_array;
}

/**
 * 在比赛中得到哪个队是主场(新)
 * 
 * 开始是在前两场比赛中找,有可以会出现前两场是比赛是同两个球队,这样会出现错误的情况
 * 修改了得到主场的方法.在每个球队中找出现strong的球队,因为是主场外面会套一个strong标签
 * 
 * @param Array $tr
 * @param file $fp
 */
function getZhuchang($tr = array(),$fp){
	$one = one_tr($tr[3], $fp);
	if(strpos($one["one"], "strong") !== false){
		return trim(strip_tags($one["one"]));
	}else{
		return trim(strip_tags($one["two"]));
	}
	
	//下面不用了,因为会出现前两个比赛为一样的情况
	$two = one_tr($tr[4], $fp);
	$one["one"] = trim(strip_tags($one["one"]));
	$one["two"] = trim(strip_tags($one["two"]));
	$two["one"] = trim(strip_tags($two["one"]));
	$two["two"] = trim(strip_tags($two["two"]));
	
	if($one["one"] == $two["one"]){
		return $one["one"];
	}
	if($one["one"] == $two["two"]){
		return $one["one"];
	}
	if($one["two"] == $two["one"]){
		return $one["two"];
	}
	if($one["two"] == $two["two"]){
		return $one["two"];
	}
	fwrite($fp, "有问题了,没有找到主场空\r\n");
}
//得到亚洲盘口
/*
function yaZhouPankou($id, $fp){
	$body = get_content("http://www.okooo.com/MatchInfo/MatchReportHandicap.php?MatchID=".$id);
	if(empty($body)){
		fwrite($fp, "得到亚洲盘口为没内容:{$id}\r\n");
		return "";
	}
	preg_match('/澳门彩票(.+?)<a href="\/MatchInfo\/MatchReportHandicpTrend.php/s',$body, $body);
	if(!empty($body[1]))
		preg_match('/class="BgGrey">(.+?)<\/td>/s',$body[1], $body);
	else 
		return "";
	return $body[1];;
}
*/
/**
 * 从传来的值中得到,日期和西甲
 */
function get_td_one($tr, $fp){
	preg_match_all('/\/" target="_blank">(.+?)<\/a><\/td>/s', $tr, $name);
	preg_match_all('/history\/" target="_blank">(.+?)<\/a><\/td>/s', $tr, $date);
	if(empty($name[1][0])){
		fwrite($fp, "处理tr_得到第一列时为空:{$tr}\r\n");
		exit;
	}
	$tr = array();
	$tr["name"] = trim($name[1][0]);
	$tr["date"] = trim($date[1][0]);

	return $tr;
}
/**
------------------
<td>西甲</td>
<td id="MatchDate"><a href="/MatchInfo/MatchReportLastMatch.php?MatchID=189483" target="_blank">12-05-06</a></td>
<td><div><a href="/Team/TeamInfoIndex.php?GroupID=2779&TeamID=23" target="_blank">奥萨苏纳</a></div></td>
<td id="MatchScore"><a href="/MatchInfo/MatchGoalsShow.php?MatchID=189483" target="_blank">1-0</a></td>
<td><div>
<a href="/Team/TeamInfoIndex.php?GroupID=2779&TeamID=33" target="_blank">
<span class="BlueLight"><strong>皇家社会</strong></span>
</a></div>
</td>
						<td class="BgGrey"><span  style="background:#FFFFB5">1.91</span></td>
<td class="BgGrey"><span >3.37</span></td>
<td class="BgGrey"><span >3.90</span></td>
<td><span  style="background:#FFFFB5">0.85</span></td>
<td>平手/半球</td>
<td><span >1.01</span></td>

------------------
传入的值为上面的字符串

要取得3,4,5列的值,返回数组

返回三列
 */
function one_tr($tr, $fp, $zhuChang=null){
	preg_match_all('/<td.*?>(.+?)<\/td>/s', $tr, $td);
	if(empty($td[1])){
		fwrite($fp, "处理tr时为空:{$tr}\r\n");
		exit;
	}
	//print_r($td[1]);exit;
	$tr = array();
	$tr["first"] = "";
	$tr["liangShai"] = trim(strip_tags($td[1][0]));
	$tr["one"] = name_span($td[1][2], $fp);
	$tr["bifen"] = strip_tags($td[1][3]);
	$tr["two"] = name_span($td[1][4], $fp);
	$tr["ok"] = "20".trim(strip_tags($td[1][1]));
	//$zhuChang为空则是找主场的;
	if(empty($zhuChang))
		return $tr;
	//  下面是取主场的                                                                             下面是三种分数都要大于2.25
	/*if(trim(strip_tags($tr["one"])) != $zhuChang || !(trim(strip_tags($td[1][5]))>2.25 && trim(strip_tags($td[1][6]))>2.25 && trim(strip_tags($td[1][7]))>2.25)){
		$tr["one"] = null;
	}*/
	return $tr;
}
/**
--------------
<div><a href="/Team/TeamInfoIndex.php?GroupID=2779&TeamID=23" target="_blank">奥萨苏纳</a></div>
--------------
<div>
<a href="/Team/TeamInfoIndex.php?GroupID=2779&TeamID=33" target="_blank">
<span class="BlueLight"><strong>皇家社会</strong></span>
</a></div>
--------------
将Class换与行内样式
 */
function name_span($td, $fp){
	if(strpos($td, "<span") === false)
		return strip_tags($td);
	else{
		preg_match("/<span class='(.*)'>/s", $td, $class);
		$name = strip_tags($td);
		
		$class_array = array(
			"bold bluetxt"=>"style='color:#36f'",
			//"BlackStrong"=>"style='color:#000'",
			"bold redtxt"=>"style='color:#f00'",
			"bold "=>"style='color:#000'"
		);
		if(empty($class_array[$class[1]])){
			fwrite($fp, "样式不存在:{$class[1]}\r\n");
		}
		return "<span {$class_array[$class[1]]}><strong>{$name}</strong></span>";
	}
}
/**
 * 取得页面内容
 */
function get_content($url){
	$data = curl($url);
	if(strlen($data) < 10000){
		sleep(1);
		$data = curl($url);
	}
	if(strlen($data) < 10000){
		sleep(1);
		$data = curl($url);
	}
	//$fp = fopen(rand(10000,99999999).".htm", "a");
	//fwrite($fp, $data);
	return $data;
}

global $getUrlCount;
$getUrlCount = 0;

/**
 * 取得页面内容
 * curl
 */
function curl($url){
	
	global $getUrlCount;
	$getUrlCount++;
	
	if($getUrlCount%5 == 0)
		sleep(15);

	if($getUrlCount%45 == 0)
		sleep(30);
return iconv("GBK", "UTF-8", file_get_contents($url));

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
	$ip = ipRand();
	//请求头信息
	$headers = array(
//		"Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
//		"Accept-Encoding:gzip, deflate",
//		"Accept-Language:zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
//		"Connection:keep-alive",
//		"Cookie:LastUrl=; FirstOKURL=http%3A//www.okooo.com/match/1/164185/history/; First_Source=www.okooo.com; __utma=56961525.1733537133.1348810154.1348810154.1348810154.1; __utmz=56961525.1348810154.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)",
//		"Host:www.okooo.com",
		"x-insight:activate",
		"User-Agent:Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1 FirePHP/0.7.1",
		"CLIENT-IP:{$ip}",
		"X-FORWARDED-FOR:{$ip}",
	);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	$output = curl_exec($ch);
	curl_close($ch);
	return iconv("GBK", "UTF-8", $output);
}
/**
 * 随机产生ip
 */
function ipRand(){
	return rand(1, 244).".".rand(1, 244).".".rand(1, 244).".".rand(1, 244);
}

/**
 * 返回目录下最大文件数
 * @param 文件夹名 $v
 */
function get_max_match($v){
	$start_lun = 1;//从第几轮开始
	$start_chang = 0;//从第第轮结束

	$data = get_all_files($v);
	foreach ($data as $value) {
		$lun = explode("_", $value);
		$chang = explode(".", $lun[1]);
		
		if($lun[0]>$start_lun){
			$start_lun = $lun[0];
			$start_chang = $chang[0];
		}else if($lun[0]==$start_lun && $chang[0]>$start_chang){
			$start_lun = $lun[0];
			$start_chang = $chang[0];
		}
	}
	return array("start_lun"=>$start_lun, "start_chang"=>$start_chang);
	
}


/**
 * 取得文件目录下.doc文件
 * @param String $path 目录
 */
function get_all_files($path, $file_type=null) {
	$list = array ();
	foreach ( glob ( $path . '/*' ) as $item ) {
		if (!is_dir ( $item ) && strpos($item, ".doc")!== false){
			$list [] = basename($item);
		}
	}
	return $list;
}

/**
 * 取得下面地址的第几轮的id,一般是10个
 * http://www.okooo.com/soccer/league/53/schedule/11079/1-34-10
 * Enter description here ...
 * @param String $href
 * @param File $fp
 */
function get_lun_url_id($href = null, $fp){
	if(empty($href))
		return null;
	
	$body = get_content($href);
	if(empty($body)){
		fwrite($fp, "主链接为空132:{$href}\r\n");
		exit;
	}
	preg_match('/class="SmallFont linkblock" (.+)<div class="scheduletable" name="status">/s',$body, $body);//取得想要的信息块
	if(empty($body[1])){
		fwrite($fp, "第一部就错了。取得想要的信息块为空:{$href}\r\n");
		exit;
	}
	preg_match_all('/<a href="\/soccer\/match\/(.+?)\/history\/" target="_blank/s',$body[1],$arr);
	
	$link_array = array();
	foreach ($arr[1] as $value) {
		//这是因为有时候会有取消的比赛,就不抓了
		if(strpos($value, "<td") === false)continue;
		$temp = explode("/", $value);
		array_push($link_array, $temp[0]);
	}
	$link_array = array_unique($link_array);
	return $link_array;
}

function get_qi_url_id($href = null, $fp){
	if(empty($href))
		return null;
	
	$body = get_content($href);
	if(empty($body)){
		fwrite($fp, "主链接为空:{$href}\r\n");
		exit;
	}
	
	preg_match('/id="table4"(.+)id="betbottom/s',$body, $body);//取得想要的信息块
	if(empty($body[1])){
		fwrite($fp, "第一部就错了。取得想要的信息块为空:{$href}\r\n");
		exit;
	}
	
	
	preg_match_all('/jsFenxi" href="\/soccer\/match\/(.+?)\/history\/" target="_blank">析/s',$body[1],$arr);
	$link_array = array_unique($arr[1]);
	return $link_array;
}